Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    accountInfo: null,
    subcount: null,
    isLoading: true,
    errorMsg: "",
    createTimeFormatted: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取本地存储的用户信息
    const userInfo = wx.getStorageSync("netease_user_info");

    if (userInfo) {
      this.setData({ userInfo });
    }

    // 加载账户信息
    this.loadAccountInfo();
  },

  /**
   * 加载账户信息
   */
  loadAccountInfo: function () {
    this.setData({
      isLoading: true,
      errorMsg: "",
    });

    const neteaseCookie = wx.getStorageSync("netease_cookie");
    if (!neteaseCookie) {
      this.setData({
        isLoading: false,
        errorMsg: "登录信息已过期，请重新登录",
      });
      return;
    }

    // 获取用户详情
    this.getUserDetail();

    // 获取用户账号信息
    this.getUserAccount();

    // 获取用户歌单、收藏等计数
    this.getUserSubcount();
  },

  /**
   * 获取用户详情
   */
  getUserDetail: function () {
    const neteaseCookie = wx.getStorageSync("netease_cookie");
    const userId = this.data.userInfo ? this.data.userInfo.userId : "";

    if (!userId) {
      console.error("无法获取用户ID");
      return;
    }

    // 确保使用http协议
    const apiUrl = "https://smartsound.top/user/detail";

    wx.request({
      url: apiUrl,
      method: "GET",
      data: {
        uid: userId,
        cookie: encodeURIComponent(neteaseCookie),
      },
      header: {
        // 防止URL被修改为https
        "force-http": "true",
      },
      success: (res) => {
        console.log("用户详情:", res.data);
        if (res.data && res.data.code === 200) {
          // 处理用户详情数据
          const profileInfo = res.data.profile || {};

          // 更新用户信息
          this.setData({
            userInfo: {
              ...this.data.userInfo,
              avatarUrl: profileInfo.avatarUrl || this.data.userInfo.avatarUrl,
              nickname: profileInfo.nickname || this.data.userInfo.nickname,
              userId: profileInfo.userId || this.data.userInfo.userId,
            },
          });

          // 存储回本地
          wx.setStorageSync("netease_user_info", this.data.userInfo);
        }
      },
      fail: (err) => {
        console.error("获取用户详情失败:", err);
      },
    });
  },

  /**
   * 获取账号信息
   */
  getUserAccount: function () {
    const neteaseCookie = wx.getStorageSync("netease_cookie");

    // 确保使用http协议
    const apiUrl = "https://smartsound.top/user/account";

    wx.request({
      url: apiUrl,
      method: "GET",
      data: {
        cookie: encodeURIComponent(neteaseCookie),
      },
      header: {
        // 防止URL被修改为https
        "force-http": "true",
      },
      success: (res) => {
        console.log("账号信息:", res.data);
        if (res.data && res.data.code === 200) {
          // 处理账号数据
          const accountInfo = res.data.account || {};
          const profile = res.data.profile || {};

          // 格式化创建时间
          let createTimeFormatted = "";
          if (accountInfo.createTime) {
            const createDate = new Date(accountInfo.createTime);
            createTimeFormatted = `${createDate.getFullYear()}年${
              createDate.getMonth() + 1
            }月${createDate.getDate()}日`;
          }

          // 合并账号和资料信息
          const mergedInfo = {
            ...accountInfo,
            ...profile,
          };

          this.setData({
            accountInfo: mergedInfo,
            createTimeFormatted: createTimeFormatted,
          });
        }
      },
      fail: (err) => {
        console.error("获取账号信息失败:", err);
        this.setData({
          errorMsg: "获取账号信息失败，请稍后再试",
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      },
    });
  },

  /**
   * 获取用户计数信息
   */
  getUserSubcount: function () {
    const neteaseCookie = wx.getStorageSync("netease_cookie");

    // 确保使用http协议
    const apiUrl = "https://smartsound.top/user/subcount";

    wx.request({
      url: apiUrl,
      method: "GET",
      data: {
        cookie: encodeURIComponent(neteaseCookie),
      },
      header: {
        // 防止URL被修改为https
        "force-http": "true",
      },
      success: (res) => {
        console.log("用户计数信息:", res.data);
        if (res.data && res.data.code === 200) {
          // 处理计数数据
          const subcountData = {
            artistCount: res.data.artistCount || 0,
            mvCount: res.data.mvCount || 0,
            createdPlaylistCount: res.data.createdPlaylistCount || 0,
            subPlaylistCount: res.data.subPlaylistCount || 0,
          };

          this.setData({ subcount: subcountData });
        }
      },
      fail: (err) => {
        console.error("获取用户计数信息失败:", err);
      },
    });
  },

  /**
   * 退出登录
   */
  logout: function () {
    wx.showModal({
      title: "确认退出",
      content: "确定要退出网易云音乐账号吗？",
      success: (res) => {
        if (res.confirm) {
          // 清除登录状态和用户信息
          wx.removeStorageSync("isNetEaseLoggedIn");
          wx.removeStorageSync("netease_cookie");
          wx.removeStorageSync("netease_user_info");

          wx.showToast({
            title: "已退出登录",
            icon: "success",
            duration: 2000,
            success: () => {
              // 延迟返回，让用户看到成功提示
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
            },
          });
        }
      },
    });
  },
});
